package com.crl.utils
{
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;

	public class BitmapUtil
	{
		private static var cache:Dictionary
		public function BitmapUtil()
		{
			throw new Error("不能创建对像");
		}
		
		
		/**
		 * 取得位图的第一个有色点.
		 * 
		 * 先取得位图的有色区域, 再复制有色区域的一个像素高度的长线.
		 * 再取得有色区域
		 * 把左上角的值相加得到第一个有色点;
		 * @param bmd
		 * @return 
		 * 
		 */		
		public static function getFirstNonTransparentPixel( bmd:BitmapData ):Point{
			/*var rect:Rectangle = bmd.getColorBoundsRect( 0xff000000, 0, false );
			if ( rect.width> 0 ){
				var temp:BitmapData = new BitmapData( rect.width, 1, true, 0 );
				temp.copyPixels( bmd, rect, new Point());
				var r2:Rectangle = temp.getColorBoundsRect( 0xff000000, 0, false );
				
				return rect.topLeft.add( r2.topLeft );
			}
			return null;*/
			
			//听说下面的这个算法更快一点;
			var hit_rect:Rectangle=new Rectangle(0,0,bmd.width,1);
			var p:Point = new Point();
			for( hit_rect.y = 0; hit_rect.y < bmd.height; hit_rect.y++ )
			{
				if( bmd.hitTest( p, 0x01, hit_rect) )
				{
					var hit_bmd:BitmapData=new BitmapData( bmd.width, 1, true, 0 );
					hit_bmd.copyPixels( bmd, hit_rect, p );
					return hit_rect.topLeft.add( hit_bmd.getColorBoundsRect(0xFF000000, 0, false).topLeft );
				}
			}
			return null;
			
		}
		
		
		/**
		 *  取得位图上所有的颜色; 
		 * @param bmd
		 * @param quality 质量;
		 * @return 
		 * 
		 */		
		public static function pickUpColors( bmd:BitmapData ,quality:uint=1):Array{
			
			//这边是不是反掉了,实际项目中应该测测;
			switch ( quality ) {
				case 1:
					_n = 16;
					break;
				case 2:
					_n = 32;
					break;
				case 3:
					_n = 64;
					break;
				default:
					_n = 32;
			}
			
			
			
			var i:uint;
			var j:uint;
			var c:uint;
			
			var arr:Array = new Array();
			var hash:Object = new Object();
			
			var x:int;
			var n:int = _n;
			var w:int = bmd.width / n;
			var h:int = bmd.height / n;
			
			for ( i = 1; i < n; i++ ) {
				x = w*i;
				
				for ( j = 1; j < n; j++ ) {
					c = bmd.getPixel( x, h*j );
					
					if ( hash[ c ] == undefined ) {
						hash[ c ] = { color:c, r:c>>20, g:c>>12&0x0f, b:c>>4&0x0f, cnt:0 };
						arr.push( hash[ c ] );
					}
					
					hash[ c ].cnt += 1;
				}
			}
			
			arr.sortOn("cnt", Array.DESCENDING | Array.NUMERIC );
			
			return reduceColor( arr );
		}
		
	}
}